#include <53func.h>
int main(int argc, char *argv[])
{
    // ./1_chatroom_select 192.168.38.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // AF_INET ipv4
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int flag = 1; // 给SO_REUSEADDR属性的参数分配内存
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    // 赋值用具体类型 传参时强转成公共类型
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    // 服务端 bind 只能绑定服务端地址
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);
    
    fd_set readyset;
    fd_set monitorset;
    FD_ZERO(&monitorset);
    FD_SET(sockfd,&monitorset);

    char buf[4096];
    int netfd[1024]; //netfd 客户端的通信socket的集合
    for(int i = 0; i < 1024; ++i){
        netfd[i] = -1;
    }// 初始化
    int curidx = 0; // 下一个要加入的netfd的下标
    while(1){
        memcpy(&readyset,&monitorset,sizeof(fd_set));
        select(1024,&readyset,NULL,NULL,NULL);
        if(FD_ISSET(sockfd,&readyset)){
            // accept
            netfd[curidx] = accept(sockfd,NULL,NULL);
            printf("curidx = %d, netfd = %d\n", curidx, netfd[curidx]);
            FD_SET(netfd[curidx],&monitorset);
            ++curidx;
        }
        for(int i = 0; i < curidx; ++i){
            if(netfd[i] != -1 && FD_ISSET(netfd[i],&readyset)){
                printf("ready, netfd = %d\n", netfd[i]);
                bzero(buf,sizeof(buf));
                ssize_t sret = recv(netfd[i],buf,sizeof(buf),0);
                if(sret == 0){
                    // 有某个客户端断开连接了
                    printf("idx = %d, netfd = %d\n",i, netfd[i]);
                    close(netfd[i]);
                    FD_CLR(netfd[i],&monitorset);
                    netfd[i] = -1;
                    continue;
                }
                for(int j = 0; j < curidx; ++j){
                    if(j == i || netfd[j] == -1){
                        continue;
                    }
                    send(netfd[j],buf,strlen(buf),0);
                }
            }
        }
    }
    return 0;
}

